package com.example.basicknowledge.MediaPlayer;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.example.basicknowledge.R;

public class MediaPlayerActivity extends AppCompatActivity implements AudioManager.OnAudioFocusChangeListener {
    private MediaPlayer testPlayer = null;
    AudioManager am = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.media_player_activity);
        testPlayer = MediaPlayer.create(this,R.raw.test_media_player);

        am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        int result = am.requestAudioFocus(this,
                // Hint: the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            startMediaPlayer(findViewById(R.id.start_player_button));
        } else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        testPlayer.release();
    }

    public void startMediaPlayer(View view){
        Toast.makeText(this,"start media player",Toast.LENGTH_SHORT).show();
        testPlayer.start();
    }

    public void pauseMediaPlayer(View view){
        Toast.makeText(this,"pause media player",Toast.LENGTH_SHORT).show();
        testPlayer.pause();
    }

    @Override
    public void onAudioFocusChange(int i) {
        if (i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
        // Pause playback
    } else if (i == AudioManager.AUDIOFOCUS_LOSS) {

        // Stop playback
    } else if (i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // Lower the volume
    } else if (i == AudioManager.AUDIOFOCUS_GAIN) {
        // Resume playback or Raise it back to normal
    }

}
}
